package com.auroramanito.uaa.validation;

import com.auroramanito.uaa.annotation.ValidEmail;
import lombok.val;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;


public class EmailValidator implements ConstraintValidator<ValidEmail,String> {
    private final static String EMAIL_PATTERN ="^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";

    @Override
    public void initialize(ValidEmail constraintAnnotation) {
        constraintAnnotation.message();
        System.out.println(constraintAnnotation);
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context)  {
        return validateEmail(value);
    }

    private boolean validateEmail(final String email){
        val pattern = Pattern.compile(EMAIL_PATTERN);
        val matcher = pattern.matcher(email);
        return matcher.matches();
    }
}
